<?php

namespace App\Imports;

use App\Models\Administrator;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CrmUserImport implements ToCollection
{
    public $count = 0;
    public $errorMessage = null;

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $headerRow = $collection->shift();
        if (!($headerRow->get(0) === '姓名' && $headerRow->get(1) === '员工号')) {
            $this->errorMessage = '错误的表头,无法识别文件';
            return;
        }

        foreach ($collection as $item) {
            $name = $item->get(0);
            $code = $item->get(1);
            if (!($name && $code)) continue;

            $user = Administrator::updateOrCreate([
                'username' => $code,
            ], [
                'name' => $name,
                'crm_username' => $code,
                'password' => bcrypt('123456'),
            ]);
            $user->roles()->sync([2, 3]);
            $this->count++;
        }
    }
}
